package controllers

import (
	"Blog/models"
	"fmt"
)

type AuthController struct{
	BaseController
}

func (c *AuthController) Index(){
	if c.Ctx.Input.IsGet(){
		limit:=2  //设置每页数量
		page,err:=c.GetInt("page")
		seaStr:=c.GetString("search")
		if err!=nil||page<1{
			page=1
		}
		nodes, err:= models.QueryNodeByPage(seaStr,page, limit)
		if err!=nil{
			c.Abort500(err)
		}
		//查询总条数，由此算出一共多少page
		num,_:=models.QueryAllCount(seaStr)
		allpage:=int(num)/limit
		if int(num)%limit!=0{
			allpage=allpage+1
		}
		c.Data["allpage"]=allpage
		c.Data["page"]=page
		c.Data["nodes"]=nodes  //返回前端查询数据
		c.TplName="index.html"
	}
}
func (c *AuthController) Message(){
	if c.Ctx.Input.IsGet(){
		pageno,err:=c.GetInt("pageno")
		if err!=nil||pageno<1{
			pageno=1
		}
		pagesize:=5
		num,messages,err:=models.QueryAllMessage(pageno,pagesize)
		if err!=nil{
			c.Abort500(err)
		}
		counts,_:=models.QueryAllMessageCount()
		allpage:=int(counts)/pagesize
		if int(counts)%pagesize!=0{
			allpage=allpage+1
		}
		c.Data["num"]=num
		c.Data["allpage"]=allpage
		c.Data["page"]=pageno
		c.Data["messages"]=messages
		c.TplName="message.html"
	}
    if c.Ctx.Input.IsPost(){
    	content:=c.GetString("content")
		message:=&models.Message{
			Content:content,
			UserId:int(c.User.ID),
			User:c.User,
		}
		err:=models.SaveMessage(message)
		if err!=nil{
			c.Abort500(err)
		}
		c.Data["json"]=map[string]interface{}{
			"code":0,
			"action":"/Auth/Message",
		}
		_ = c.ServeJSON()
	}
}
func (c *AuthController) Comment(){
	key:=c.GetString("key")
	num,node,err:=models.QueryNodeByKey(key)
	if err!=nil&&num==0{
		c.Abort500(err)
	}
	if c.Ctx.Input.IsPost(){
        content:=c.GetString("content")
        message:=&models.Message{
			Content:content,
			UserId:int(c.User.ID),
			User:c.User,
			NodeKey:key,
		}
        err:=models.SaveMessage(message)
        if err!=nil{
        	c.Abort500(err)
		}
		c.Data["json"]=map[string]interface{}{
			"code":0,
			"action":"/Node/Details/?key="+key,
		}
		_ = c.ServeJSON()
	}
	c.Data["node"]=node
	c.TplName="comment.html"
}

func (c *AuthController) Count(){
    num,err:=models.QueryAllMessageCount()
    fmt.Println(num)
    if err!=nil{
    	c.Abort500(err)
	}
   c.Data["json"]=map[string]interface{}{
   	    "count":num,
   }
	_ = c.ServeJSON()
}




